package com.zhangtai.modules.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhangtai.common.annotation.SysAuthorityLog;
import com.zhangtai.modules.controller.aouthLogin.LoginController;
import com.zhangtai.modules.dao.ComputerSubsidyDao;
import com.zhangtai.modules.dao.EmployeeSecondmentDao;
import com.zhangtai.modules.dao.ImgUrlDao;
import com.zhangtai.modules.dto.EmployeeSecondmentDto;
import com.zhangtai.modules.entity.common.ImgUrlEntity;
import com.zhangtai.modules.entity.employee.EmployeeSecondmentEntity;
import com.zhangtai.modules.entity.salary.ComputerSubsidyEntity;
import com.zhangtai.modules.service.common.ImgUrlService;
import com.zhangtai.modules.service.employee.EmployeeSecondmentService;
import com.zhangtai.modules.vo.EmployeeSecondmentVo;
import com.zhangtai.utils.BeanUtilsMabach;
import com.zhangtai.utils.DateUtils;
import com.zhangtai.utils.PageResult;
import com.zhangtai.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;




/**
 * 员工借调
 */
@Api(tags="员工借调接口")
@RestController
@RequestMapping("secondment")
@Slf4j
public class EmployeeSecondmentController {
    @Autowired
    private EmployeeSecondmentService employeeSecondmentService;
    @Autowired
    private LoginController loginController;
    @Autowired
    private JobController jobController;
    @Autowired
    private EmployeeSecondmentDao employeeSecondmentDao;
    @Autowired
    private ImgUrlDao imgUrlDao;

    @Autowired
    private ImgUrlService imgUrlService;
    @Autowired
    private ComputerSubsidyDao computerSubsidyDao;
    /**
     * 列表员工借调
     */
    @GetMapping("/queryEmployeeSecondmentPage")
    @ApiOperation(value = "分页查询员工借调信息")
    public R queryEmployeeSecondmentPage(
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "status",required = false) List<Integer> status,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest request) throws Exception {
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request,null,false);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        //获得借调后的公司组权限
        PageResult result1 = employeeSecondmentService.queryPage(orgIds,name,status,pageNum,pageSize);
        List<EmployeeSecondmentEntity> employeeSecondmentEntityList1=  result1.getList();
        for (EmployeeSecondmentEntity employeeSecondmentEntity:employeeSecondmentEntityList1){

             orgIds.add(employeeSecondmentEntity.getSecondmentUnitId());
        }

        PageResult result = employeeSecondmentService.queryPage(orgIds,name,status,pageNum,pageSize);


         List<EmployeeSecondmentEntity> employeeSecondmentEntityList=  result.getList();
         List<EmployeeSecondmentDto> employeeSecondmentDtoList=new ArrayList<>();
         for (EmployeeSecondmentEntity employeeSecondmentEntity:employeeSecondmentEntityList){
             EmployeeSecondmentDto employeeSecondmentDto = BeanUtilsMabach.doToDto(employeeSecondmentEntity, EmployeeSecondmentDto.class);
             if(employeeSecondmentDto.getJobId()!=null) employeeSecondmentDto.setJobName(jobController.getJobName(employeeSecondmentDto.getJobId()));
             if(employeeSecondmentDto.getOrgId()!=null) employeeSecondmentDto.setOrgName(jobController.getOrgNameById(employeeSecondmentDto.getOrgId()));
             if(employeeSecondmentDto.getUnitId()!=null) employeeSecondmentDto.setUnitName(jobController.getOrgNameById(employeeSecondmentDto.getUnitId()));
             if(employeeSecondmentDto.getSecondmentJobId()!=null) employeeSecondmentDto.setSecondmentJobName(jobController.getJobName(employeeSecondmentDto.getSecondmentJobId()));
             if(employeeSecondmentDto.getSecondmentOrgId()!=null) employeeSecondmentDto.setSecondmentOrgName(jobController.getOrgNameById(employeeSecondmentDto.getSecondmentOrgId()));
             if(employeeSecondmentDto.getSecondmentUnitId()!=null) employeeSecondmentDto.setSecondmentUnitName(jobController.getOrgNameById(employeeSecondmentDto.getSecondmentUnitId()));
             employeeSecondmentDtoList.add(employeeSecondmentDto);
         }


        result.setList(employeeSecondmentDtoList);
        return R.ok(result);
    }


    /**
     * 删除员工调动信息
     */
    @DeleteMapping("/deleteEmployeeSecondment")
    @ApiOperation(value = "删除员工调动信息")
    @SysAuthorityLog(value = "删除员工调动信息")
    @Transactional
    public R deleteEmployeeSecondment(@RequestParam("id") String id){
        employeeSecondmentDao.deleteById(id);
        return R.ok();
    }


    /**
     * 修改
     */
    @PostMapping("/saveAndUpdateEmployeeSecondment")
    @ApiOperation(value = "保存或修改员工调动信息")
    @SysAuthorityLog(value = "保存或修改员工调动信息")
    @Transactional
    public R saveAndUpdateEmployeeSecondment(@RequestBody EmployeeSecondmentVo employeeSecondmentVo, HttpServletRequest request) throws Exception {
        JSONObject data =loginController.getUserInfo(request).getData();
        if (ObjectUtils.isEmpty(data)) {
            return  R.error("请先登录");
        }
        EmployeeSecondmentEntity employeeSecondmentEntity = BeanUtilsMabach.doToDto(employeeSecondmentVo, EmployeeSecondmentEntity.class);
        if(!CollectionUtils.isEmpty(employeeSecondmentVo.getFileUrlList())){
            saveFile(employeeSecondmentEntity.getOid(),employeeSecondmentVo.getFileUrlList(), "借调附件",23);
            employeeSecondmentEntity.setFileUrl(ListToString(employeeSecondmentVo.getFileUrlList()));
        }
        R r;
        if(employeeSecondmentEntity.getId()==null){
            employeeSecondmentEntity.setCreateCode(data.getString("usercode"));
            employeeSecondmentEntity.setCreateName(data.getString("name"));
            employeeSecondmentEntity.setCreateTime(new Date());
            employeeSecondmentEntity.setStatus(0);
         r=  employeeSecondmentService.saveE(employeeSecondmentEntity) ;
        }else{
          r=  employeeSecondmentService.updateByIdE(employeeSecondmentEntity);
        }
        return r;
    }

    @PostMapping("/getComputerSubsidyByOid")
    @ApiOperation("根据oid查询异地补贴")
    public R getComputerSubsidyByOid(@RequestParam(value = "oid") String oid){
        Date date=new Date();
        List<ComputerSubsidyEntity>  computerSubsidyEntityList= computerSubsidyDao.selectList(new QueryWrapper<ComputerSubsidyEntity>()
                .eq("oid",oid)
                .eq("type",3)
                .eq("approve_status",2)
                .eq("status",1)
                .ge("end_date", DateUtils.formatYM(date)).orderByDesc("end_date"));
        return R.ok(computerSubsidyEntityList);
    }

    //附件保存
    public void saveFile(Long oid, ArrayList<String> fileList,String name,Integer type){
        for (String s : fileList) {
            imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("url", s).eq("type", type));
            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setName(name);
            imgUrlEntity.setOid(oid);
            imgUrlEntity.setType(type);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlEntity.setUrl(s);
            imgUrlService.saveE(imgUrlEntity);
        }

    }
    public String ListToString(ArrayList<String> fileUrlList){
        String Url="";
        for ( String s:fileUrlList){
            Url+=s+",";
        }
        return Url.substring(0,Url.length()-1);
    }
}
